<template>
  <div class="app-page">
    <div class="content">
      <el-card class="left">
        <div slot="header" class="clearfix">
          <span>机构</span>
        </div>
        <el-tree
          ref="tree"
          node-key="id"
          highlight-current
          :data="orgList"
          :props="defaultProps"
          @current-change="handleTreeSelected"
        />
      </el-card>
      <el-card class="right">
        <div slot="header" class="clearfix">
          <span>角色</span>
        </div>
        <div class="app-table-action-wrap">
          <auth-button auth-key="e_1_1" type="primary" icon="el-icon-plus" size="small" @click="handleAdd">
            新增
          </auth-button>
        </div>
        <table-paging
          :table-list="tableList"
          :table-column="tableColumn"
          :table-btn-width="240"
          :table-paging="tablePaging"
          :table-total="tableTotal"
          @pagingChange="handlePaginChange"
        />
      </el-card>

      <dialog-form
        width="400px"
        :title="dialogTitle"
        :visible="dialogVisible"
        :form-attrs="{formData: modalFormData, renderFormItem, formButtons, labelWidth: '120px', isHideButtons}"
        @close="() => (dialogVisible = false)"
      />

      <data-auth
        ref="dataAuth"
        :visible.sync="dataAuthVisible"
        :org-list="orgDropList"
        :is-hide-buttons="isHideButtons"
        :modal-form-data="modalFormData"
        @handleSubmit="handleModalSubmit"
      />

      <operate-auth
        ref="operateAuth"
        :org-list="orgDropList"
        :visible.sync="operateAuthVisible"
        :is-hide-buttons="isHideButtons"
        :modal-form-data="modalFormData"
        @handleSubmit="handleModalSubmit"
      />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchOrgFindPage } from '@/api/basicinfo/system/organization'
import { fetchRoleFindPage, fetchRoleGet, fetchRoleAdd, fetchRoleUpdate, fetchRoleDelete } from '@/api/basicinfo/system/role'
import { createTreeList } from '@/utils'
import { TablePaging, DialogForm, AuthButton } from '@/components'
import { tableColumn, modalFormItem, formButtons } from './config'
import OperateAuth from './components/operateAuth'
import DataAuth from './components/dataAuth'

export default {
  name: 'Role',
  components: { TablePaging, DialogForm, DataAuth, OperateAuth, AuthButton },
  data() {
    return {
      cardBodyStyle: { // card body 样式
        padding: 0
      },
      orgList: [], // 机构列表
      defaultProps: {
        children: 'children',
        label: 'orgName'
      },

      orgDropList: [], // 机构下拉

      selectedOrgId: 0, // 机构选中 id

      tableList: [], // table数据
      tableColumn: tableColumn(this.handleEdit, this.handleOperateAuth, this.handleDataAuth, this.handleDelete), // tableColumn 配置
      tableTotal: 0,
      tablePaging: {
        page: 1,
        pagesize: 10
      },

      dialogVisible: false,
      dialogTitle: '新增',

      dataAuthVisible: false,

      operateAuthVisible: false,

      modalFormData: {},
      renderFormItem: [],
      formButtons: formButtons(this.handleModalSubmit, this.hanleClose)
    }
  },
  computed: {
    ...mapGetters(['userOrgId']),
    isHideButtons() {
      return this.userOrgId !== this.selectedOrgId
    }
  },
  created() {
    this.postOrgFindPage()
  },
  methods: {
    handleTreeSelected(data, node) { // 机构选中
      this.selectedOrgId = data.id
      this.searchFormData = {
        orgId: this.selectedOrgId
      }
      this.postFindPage()
    },

    handleAdd() { // 点击添加机构
      if (!this.selectedOrgId) {
        this.$message.warning('请选择机构')
        return false
      }
      if (this.selectedOrgId !== this.userOrgId) {
        this.$message.warning('不允许操作其他机构数据')
        return false
      }
      this._setModalData()
    },

    handleEdit(id) { // 修改
      this.postGet(id, 'edit')
    },

    handleDelete(id) { // 删除
      if (this.selectedOrgId !== this.userOrgId) {
        this.$message.warning('不允许操作其他机构数据')
        return false
      }
      this.postDelete(id)
    },

    handleModalSubmit(values) { // 弹窗提交
      if (values.id) {
        this.postUpdate(values)
        return false
      }
      this.postAdd(values)
    },

    hanleClose() { // 关闭
      this.dialogVisible = false
    },

    handleDataAuth(id, e) { // 数据权限弹窗
      this.postGet(e.id, 'dataAuth', e.orgId)
    },

    handleOperateAuth(id, e) {
      this.postGet(id, 'operateAuth')
    },

    handlePaginChange(pageInfo) { // 分页改变
      this.tablePaging = pageInfo
      this.postFindPage()
    },

    _setModalData(title = '新增', visible = true, modalFormData = { orgId: this.selectedOrgId }) { // 设置弹窗
      this.modalFormData = modalFormData
      this.dialogTitle = title
      this.dialogVisible = visible
    },

    _setDataAuthData(data, orgId) { // 设置 dataAuth 数据
      if (data.deptIds) {
        data.deptIdList = data.deptIds.split(',').map(item => item)
      }
      data.orgIdList = data.orgIds.split(',')
      data.orgIdList = data.orgIdList.map(item => +item)
      this.modalFormData = data
      this.dataAuthVisible = true
      this.$refs.dataAuth.postDeptFindPage(orgId)
    },

    _setOperateAuthData(data) { // 设置 OperateAuth 数据值
      this.modalFormData = data
      this.operateAuthVisible = true
    },

    postOrgFindPage() { // 获取机构列表
      fetchOrgFindPage().then(res => {
        this.orgDropList = res.records.map(item => ({ key: item.id, value: item.orgName, parentId: item.parentOrgId }))
        this.orgList = createTreeList(res.records)
        this.renderFormItem = modalFormItem(this.orgDropList)
      })
    },

    postFindPage() { // 获取人员列表
      fetchRoleFindPage({ ...this.searchFormData, ...this.tablePaging }).then(res => {
        const { records, current, size, total } = res
        this.tableList = records
        this.tablePaging = {
          page: current,
          pagesize: size
        }
        this.tableTotal = total
      })
    },

    postAdd(values) { // 新增
      fetchRoleAdd(values).then(() => {
        this.$message.success('新增成功!')
        this.dialogVisible = false
        this.postFindPage()
      })
    },

    postGet(id, type, orgId) { // 获取详情
      fetchRoleGet({ id }).then(res => {
        type === 'edit' && this._setModalData('修改', true, res)
        type === 'dataAuth' && this._setDataAuthData(res, orgId)
        type === 'operateAuth' && this._setOperateAuthData(res)
      })
    },

    postUpdate(values) { // 更新
      fetchRoleUpdate(values).then(() => {
        this.dialogVisible = false
        this.dataAuthVisible = false
        this.operateAuthVisible = false
        this.$message.success('修改成功!')
        this.postFindPage()
      })
    },

    postDelete(id) { // 删除
      fetchRoleDelete({ id }).then(() => {
        this.$message.success('删除成功!')
        this.postFindPage()
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.app-page {
  .content {
    min-height: calc(100vh - 132px);
    display: flex;
    justify-content: flex-start;

    .left {
      min-width: 240px;
    }
    .right {
      width: 100%;
      box-sizing: border-box;
      overflow: auto;

      .add-btn {
        float: right;
      }
    }

    .table {
      clear: both;
      width: 100%;
    }

    .title {
      margin-top: 20px;
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 20px;
    }
  }
}
</style>
